import {
  EquipmentType,
  AddOrUpdateEquipmentQueryType,
  GetEquipmentListQueryType,
  EquipmentStatus,
} from "../types/equipment";

// Mock数据
const mockEquipmentList: EquipmentType[] = [
  {
    id: "1",
    name: "1234567890",
    typeId: "1",
    code: "1234567890",
    model: "1234567890",
    chargeUserCode: "1234567890",
    status: EquipmentStatus.IDLE,
    location: "1234567890",
    belong: "1234567890",
    purchaseDate: 1234567890,
    deliveryDate: 1234567890,
    useYears: 1,
    purchasePrice: 1000,
    description1: "1234567890",
    description2: "1234567890",
    photoIds: ["photo1", "photo2", "photo3"],
    documentIds: ["doc1", "doc2", "doc3"],
  },
  {
    id: "2",
    name: "1234567890",
    typeId: "1",
    code: "1234567890",
    model: "1234567890",
    chargeUserCode: "1234567890",
    status: EquipmentStatus.IDLE,
    location: "1234567890",
    belong: "1234567890",
    purchaseDate: 1234567890,
    deliveryDate: 1234567890,
    useYears: 1,
    purchasePrice: 1000,
    description1: "1234567890",
    description2: "1234567890",
    photoIds: ["photo4", "photo5"],
    documentIds: ["doc4"],
  },
  {
    id: "3",
    name: "1234567890",
    typeId: "1",
    code: "1234567890",
    model: "1234567890",
    chargeUserCode: "1234567890",
    status: EquipmentStatus.IDLE,
    location: "1234567890",
    belong: "1234567890",
    purchaseDate: 1234567890,
    deliveryDate: 1234567890,
    useYears: 1,
    purchasePrice: 1000,
    description1: "1234567890",
    description2: "1234567890",
  },
  {
    id: "4",
    name: "1234567890",
    typeId: "1",
    code: "1234567890",
    model: "1234567890",
    chargeUserCode: "1234567890",
    status: EquipmentStatus.IDLE,
    location: "1234567890",
    belong: "1234567890",
    purchaseDate: 1234567890,
    deliveryDate: 1234567890,
    useYears: 1,
    purchasePrice: 1000,
    description1: "1234567890",
    description2: "1234567890",
  },
  {
    id: "5",
    name: "1234567890",
    typeId: "1",
    code: "1234567890",
    model: "1234567890",
    chargeUserCode: "1234567890",
    status: EquipmentStatus.IDLE,
    location: "1234567890",
    belong: "1234567890",
    purchaseDate: 1234567890,
    deliveryDate: 1234567890,
    useYears: 1,
    purchasePrice: 1000,
    description1: "1234567890",
    description2: "1234567890",
  },
];

// 生成唯一ID
const generateId = (): string => {
  return Date.now().toString() + Math.random().toString(36).substr(2, 9);
};

// 模拟延迟
const delay = (ms = 300): Promise<void> => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

// 获取设备列表的mock
export const mockGetEquipmentList = async (
  params: GetEquipmentListQueryType
): Promise<{
  status: number;
  data: {
    list: EquipmentType[];
    page: number;
    size: number;
    totalElements: number;
    totalPages: number;
  };
  message: string;
}> => {
  await delay();

  return {
    status: 0,
    data: {
      list: mockEquipmentList,
      page: params.page || 1,
      size: params.size || 50,
      totalElements: mockEquipmentList.length,
      totalPages: params.size
        ? Math.ceil(mockEquipmentList.length / params.size)
        : 1,
    },
    message: "获取设备列表成功",
  };
};

// 添加或更新设备的mock
export const mockAddOrUpdateEquipment = async (
  params: AddOrUpdateEquipmentQueryType
): Promise<{ status: number; data: EquipmentType | null; message: string }> => {
  await delay();

  try {
    // 编辑设备
    if (params.id) {
      const index = mockEquipmentList.findIndex(
        (equipment) => equipment.id === params.id
      );

      if (index === -1) {
        return {
          status: 1,
          data: null,
          message: "设备不存在",
        };
      }

      // 更新设备信息
      const updatedEquipment: EquipmentType = {
        ...mockEquipmentList[index],
        ...Object.fromEntries(
          Object.entries(params).filter(
            ([_, value]) => value !== null && value !== undefined
          )
        ),
      } as EquipmentType;

      mockEquipmentList[index] = updatedEquipment;

      return {
        status: 0,
        data: updatedEquipment,
        message: "更新设备成功",
      };
    }
    // 添加新设备
    else {
      // 验证必填字段
      if (!params.name || !params.typeId) {
        return {
          status: 1,
          data: null,
          message: "姓名和类型为必填项",
        };
      }

      // 检查类型是否已存在
      const existingEquipment = mockEquipmentList.find(
        (equipment) => equipment.typeId === params.typeId
      );
      if (existingEquipment) {
        return {
          status: 1,
          data: null,
          message: "该类型已存在",
        };
      }

      const newEquipment: EquipmentType = {
        id: generateId(),
        name: params.name || "",
        typeId: params.typeId || "",
        code: params.code || "",
        model: params.model || "",
        chargeUserCode: params.chargeUserCode || "",
        status: params.status || "IDLE",
        location: params.location || "",
        belong: params.belong || "",
        purchaseDate: params.purchaseDate || 0,
        deliveryDate: params.deliveryDate || 0,
        useYears: params.useYears || 1,
        purchasePrice: params.purchasePrice || 1000,
        description1: params.description1 || "",
        description2: params.description2 || "",
      };

      mockEquipmentList.unshift(newEquipment); // 添加到列表开头

      return {
        status: 0,
        data: newEquipment,
        message: "添加设备成功",
      };
    }
  } catch (error) {
    return {
      status: 1,
      data: null,
      message: "操作失败，请重试",
    };
  }
};

// 删除设备的mock（可选，如果需要的话）
export const mockDeleteEquipment = async (
  id: string
): Promise<{ status: number; data: null; message: string }> => {
  await delay();

  const index = mockEquipmentList.findIndex((equipment) => equipment.id === id);

  if (index === -1) {
    return {
      status: 1,
      data: null,
      message: "设备不存在",
    };
  }

  mockEquipmentList.splice(index, 1);

  return {
    status: 0,
    data: null,
    message: "删除设备成功",
  };
};

// 根据ID获取单个设备的mock（可选）
export const mockGetEquipmentById = async (
  id: string
): Promise<{ status: number; data: EquipmentType | null; message: string }> => {
  await delay();

  const equipment = mockEquipmentList.find((equipment) => equipment.id === id);

  if (!equipment) {
    return {
      status: 1,
      data: null,
      message: "设备不存在",
    };
  }

  return {
    status: 0,
    data: equipment,
    message: "获取设备详情成功",
  };
};

// 更新设备文件的mock
export const mockUpdateDeviceFiles = async (params: {
  deviceId: string;
  photoIds: string[];
  documentIds: string[];
}): Promise<{ status: number; data: any; message: string }> => {
  await delay();

  const equipment = mockEquipmentList.find((equipment) => equipment.id === params.deviceId);

  if (!equipment) {
    return {
      status: 1,
      data: null,
      message: "设备不存在",
    };
  }

  // 更新设备的文件ID列表
  equipment.photoIds = params.photoIds;
  equipment.documentIds = params.documentIds;

  return {
    status: 0,
    data: equipment,
    message: "更新设备文件成功",
  };
};
